package com.future.common.interceptor;

import com.future.common.bean.Result;
import com.future.common.exception.AppException;
import com.future.common.exception.AuthenticationException;
import com.future.common.exception.BadRequestException;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class AppExceptionInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		Boolean devMode = PropKit.getBoolean("devMode");
		Controller controller = inv.getController();
		Result result = new Result();
		result.set_success(true);
		try {
			inv.invoke();
		} catch (AppException e) {
			result.set_success(false);
			if (devMode) {
				e.printStackTrace();
			}
			result.set_message(e.getMessage());
			result.setCode("200");
			controller.renderJson(result);
		//认证异常
		}catch(AuthenticationException e){
			result.set_success(false);
			if (devMode) {
				e.printStackTrace();
			}
			result.set_message(e.getMessage());
			result.setCode("401");
			controller.renderJson(result);
		}catch(BadRequestException e){
			result.set_success(false);
			if (devMode) {
				e.printStackTrace();
			}
			log.error("请求异常", e);
			result.set_message(e.getMessage());
			result.setCode("400");
			controller.renderJson(result);
		}catch (Exception e) {
			result.set_success(false);
			if (devMode) {
				e.printStackTrace();
			}
			log.error("内部异常", e);
			result.set_message(e.getMessage());
			result.setCode("500");
			controller.renderJson(result);
		}
	}
}